package com.andrew.apolloMod.mediastore;

import java.io.File;

import org.gl.android.utils.lg;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

public class SDcard {
	public static final int STARTED = 0;
	public static final int FINISHED = 1;
	ScanSdFilesReceiver scanReceiver;
	private Handler scanHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case STARTED:
				// MyDialog scanDialog = new MyDialog(LocalList.this);
				// scanAlertDialog = scanDialog.scanFile();
				// scanAlertDialog.show();
				lg.d(this, "showing");
				break;
			case FINISHED:
				// ArrayList<Song> tempSongs = ReadFileList.readDataFromSD(
				// LocalList.this, LOCAL);
				// if (tempSongs != null && tempSongs.size() > 0) {
				// if (songs != null && songs.size() > 0) {
				// songs.clear();
				// songs.addAll(tempSongs);
				// songAdapter.notifyDataSetChanged();
				// } else {
				// songs = new ArrayList<Song>();
				// songs.addAll(tempSongs);
				// initSong_lv();
				// }
				// } else {
				// Toast.makeText(LocalList.this, "SD卡中没有歌曲，请添加后再扫描",
				// Toast.LENGTH_SHORT).show();
				// }
				// Log.i(TAG, "finish");
				// if (scanAlertDialog != null && scanAlertDialog.isShowing()) {
				// scanAlertDialog.dismiss();
				// }
				lg.d(this, "FINISHED");
				context.unregisterReceiver(scanReceiver);
				break;
			default:
				break;
			}
		}
	};
	private Context context;

	public void notifMediaStoreScan(Context context, String path) {
		this.context = context;
		IntentFilter intentFilter = new IntentFilter(
				Intent.ACTION_MEDIA_SCANNER_STARTED);
		intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
		intentFilter.addDataScheme("file");
		scanReceiver = new ScanSdFilesReceiver();
		context.registerReceiver(scanReceiver, intentFilter);
		context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
				.parse("file://" + Environment.getExternalStorageDirectory()
						+ File.separator + path)));
		lg.d(this, "notifMediaStoreScaner");
	}

	private class ScanSdFilesReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action)) {
				scanHandler.sendEmptyMessage(STARTED);
			}
			if (Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)) {
				scanHandler.sendEmptyMessage(FINISHED);
			}
		}
	}
}
